//
//  QuestionBrowseViewController.m
//  jinnengExam
//
//  Created by mac on 2020/8/13.
//  Copyright © 2020 jznrj. All rights reserved.
//

#import "QuestionBrowseViewController.h"
#import "BrowseBottomView.h"
#import "PBFlatBarButtonItems.h"
@interface QuestionBrowseViewController ()<OperateBarDelegate>
@property(nonatomic,strong) BrowseBottomView *bottomView;
@property(nonatomic,strong) NSArray *array;
@property(nonatomic) int loadingIndex;
@property (nonatomic, strong) dispatch_source_t timer;
@property(nonatomic) int learnTime;

@property (nonatomic, strong) UIButton *  navrightBtn;
@property (nonatomic) int time;
@property(nonatomic) int viewTime;

@property(nonatomic,strong) NSDate *startTime;
@property(nonatomic) int startIndex;
@end

@implementation QuestionBrowseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"试题学习";
    // Do any additional setup after loading the view.

    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    self.loadingIndex  = [[ud objectForKey:[NSString stringWithFormat:@"questionBank_%d",self.questionBankId]] intValue];
    self.startIndex = self.loadingIndex;
    self.startTime = [[NSDate alloc]init];
    
    UINavigationBar * bar = self.navigationController.navigationBar;
    UIImage *bgImage = [ColorUtil navigationBarColor:[ColorUtil titleColor] BarSize:bar.frame alphe:1.0];
    [bar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];
    [bar setTintColor:[UIColor whiteColor]];
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]}forState:UIControlStateNormal];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,nil]];
    
    UIBarButtonItem *back = [PBFlatBarButtonItems backBarButtonItemWithTarget:self selector:@selector(goBack)];
    [self.navigationItem setLeftBarButtonItem:back];
    
    self.learnTime = 0;
    self.viewTime = 0;
    
    [self initView];

}

-(void)viewWillDisappear:(BOOL)animated{
    if (self.timer!=nil) {
        dispatch_source_cancel(self.timer);
        self.timer = nil;
    }
}

-(void) viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = NO;
    [self requestViewTime];
}
//- (void)didMoveToParentViewController:(UIViewController*)parent{
//
//    [super didMoveToParentViewController:parent];
//    if(!parent){
//
//    }
//
//}
-(void) goBack{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setInteger:self.loadingIndex forKey:[NSString stringWithFormat:@"questionBank_%d",self.questionBankId]];
    
    NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
    fmt.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    [fmt setDateStyle:NSDateFormatterMediumStyle];
    [fmt setTimeStyle:NSDateFormatterShortStyle];
    fmt.dateFormat = @"yyyy-MM-dd'T'hh:mm:ss.SSS'Z'";
    
    NSString *url = [NSString stringWithFormat:@"%@/questionBrowse/addBrowseRecord" ,[URLUtil hostName]];
    NSDictionary *params = @{@"questionBankId":[NSString stringWithFormat:@"%d",self.questionBankId],
                             @"userId":[NSString stringWithFormat:@"%d",self.loginDto.userId],
                             @"startNum":[NSString stringWithFormat:@"%d",self.startIndex],
                             @"startTime":[fmt stringFromDate:self.startTime],
                             @"endNum":[NSString stringWithFormat:@"%d",self.loadingIndex],
                             @"endTime":[fmt stringFromDate:[[NSDate alloc]init]],
                             @"viewTime":[NSString stringWithFormat:@"%d",self.viewTime],
      };
    
    [JZNRequestUtil requestUrl:url requestParams:params success:^(DataResult *dataResult) {
    } failure:^(NSError *error) {
        
    }];
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void) initView{
    self.navrightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
    [self.navrightBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 20, 0, -10)];
    self.navrightBtn.titleLabel.textAlignment=NSTextAlignmentRight;
    [self.navrightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.navrightBtn.titleLabel.font=[UIFont systemFontOfSize:14];
    
     [self.navrightBtn setTitle:@"00:00" forState:UIControlStateNormal];
    
    UIBarButtonItem *naviItem = [[UIBarButtonItem alloc] initWithCustomView:self.navrightBtn];
    self.navigationItem.rightBarButtonItem=naviItem;
    
    [self.view addSubview:self.jznWebView];
    self.jznWebView.scrollView.bounces = NO;
    [self.jznWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        if (@available(iOS 11.0, *)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        } else {
            make.top.equalTo(self.view);
        }
        make.bottom.equalTo(self.view).offset(-52);
    }];

    [self.view addSubview:self.loadingProgressView];
    [self.loadingProgressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
    [self.loadingProgressView startAnimating];
    
    self.bottomView = [[BrowseBottomView alloc]init];
    self.bottomView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin;
    self.bottomView.delegate = self;
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
       if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(self.view);
        }
        make.width.equalTo(self.view);
        make.height.equalTo(@52);
    }];
    [self.bottomView setupView];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.jznWebView loadLocalFile:@"/ios_jinneng/questionBrowse" type:@"html"];
    
    [self registerJSFunction];
    
    [self.view addSubview:self.loadingProgressView];
    [self.loadingProgressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
    

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    [self findQuestionByMuluId];
}

-(void) findQuestionByMuluId{
    NSString *url = [NSString stringWithFormat:@"%@/question/findQuestionByMuluId" ,[URLUtil hostName]];
    NSDictionary *params = @{@"questionBankId":[NSString stringWithFormat:@"%d",self.questionBankId]};
    [self.loadingProgressView startAnimating];
    
    [JZNRequestUtil requestUrl:url requestParams:params success:^(DataResult *dataResult) {
        [self.loadingProgressView stopAnimating];
        if(dataResult.code == 0){
            self.array = dataResult.data;
            NSString *loadPaper = [NSString stringWithFormat:@"loadPaper(%@)",[[self.array objectAtIndex:self.loadingIndex] mj_JSONString]];
            [self.jznWebView evaluateJavaScript:loadPaper completionHandler:nil];
            
            NSString *loadQuestion = [NSString stringWithFormat:@"loadQuestion(%d)",self.loadingIndex];
            [self.jznWebView evaluateJavaScript:loadQuestion completionHandler:nil];
            
            NSString *loadTotal = [NSString stringWithFormat:@"loadTotal(%d)",self.array.count];
            [self.jznWebView evaluateJavaScript:loadTotal completionHandler:nil];
        }else {
        }
    } failure:^(NSError *error) {
        
    }];
    
}

-(void) requestViewTime{
    NSString *url = [NSString stringWithFormat:@"%@/questionBrowse/findUserLearnTime" ,[URLUtil hostName]];
    NSDictionary *params = @{@"userId":[NSString stringWithFormat:@"%d",self.loginDto.userId]};
    [JZNRequestUtil requestUrl:url requestParams:params success:^(DataResult *dataResult) {
        [self.loadingProgressView stopAnimating];
        if(dataResult.code == 0){
            self.learnTime = [dataResult.data intValue];
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
            dispatch_source_set_event_handler(_timer, ^{
                
                int second = self.learnTime%60;
                int min = self.learnTime/60;
                NSString *strTime;
                
                if (min < 10 && second <10){
                    strTime = [NSString stringWithFormat:@"0%d: 0%d",min,second];
                }else if (second <10) {
                    strTime = [NSString stringWithFormat:@"%d: 0%d",min,second];
                }else if (min < 10){
                    strTime = [NSString stringWithFormat:@"0%d: %d",min,second];
                }else{
                    strTime = [NSString stringWithFormat:@"%d: %d",min,second];
                    
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    
                    [self.navrightBtn setTitle:strTime forState:UIControlStateNormal];
                    
                });
                self.learnTime++;
                self.viewTime++;

            });
            dispatch_resume(_timer);
        }else {
        }
    } failure:^(NSError *error) {
        
    }];
}

-(void) registerJSFunction{
    [self.webViewBridge registerHandler:@"indexError" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSString *error = data[@"errorMessage"];
        dispatch_async(dispatch_get_main_queue(), ^(){
            [[UIApplication sharedApplication].delegate.window makeToast:error];
        });
    }];
    
    [self.webViewBridge registerHandler:@"changeIndex" handler:^(id data, WVJBResponseCallback responseCallback) {
        int index = [data[@"index"] intValue];
        self.loadingIndex = index;
        NSString *loadPaper = [NSString stringWithFormat:@"loadPaper(%@)",[[self.array objectAtIndex:index] mj_JSONString]];
        [self.jznWebView evaluateJavaScript:loadPaper completionHandler:nil];
        
        NSString *loadQuestion = [NSString stringWithFormat:@"loadQuestion(%d)",index];
        [self.jznWebView evaluateJavaScript:loadQuestion completionHandler:nil];
       }];
}

- (void)onButtonAction:(NSInteger)offset{
      if (offset == 0) {
          
          NSString *pre = @"pre()";
          [self.jznWebView evaluateJavaScript:pre completionHandler:nil];
          self.bottomView.showResultButton.hidden = NO;
          self.bottomView.hideResultButton.hidden = YES;
      }else if(offset == 1){
          
          NSString *next = @"next()";
          [self.jznWebView evaluateJavaScript:next completionHandler:nil];
          self.bottomView.showResultButton.hidden = NO;
          self.bottomView.hideResultButton.hidden = YES;
          
      } else if(offset == 2) {
          NSString *showAnswer = @"showAnswer()";
          [self.jznWebView evaluateJavaScript:showAnswer completionHandler:nil];
          self.bottomView.showResultButton.hidden = YES;
          self.bottomView.hideResultButton.hidden = NO;
      }else if(offset == 3) {
          NSString *hidenAnswer = @"hidenAnswer()";
          [self.jznWebView evaluateJavaScript:hidenAnswer completionHandler:nil];
          self.bottomView.showResultButton.hidden = NO;
          self.bottomView.hideResultButton.hidden = YES;
      }
}

@end
